<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="formData.roleId">
          <el-option  v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="音频文件" prop="fileId">
        <CustomUploadFile :limitSize="100" :fileTypeList="['mp3', 'aac']" :show-play-btn="true" :default-list="defaultFileList"  @upload-finish="uploadFinish" />
      </el-form-item>
      <el-form-item label="场景名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入场景名称" />
      </el-form-item>
      <el-form-item label="心跳指数" prop="heartbeatLevel">
        <el-input-number :min="0" :max="7" v-model="formData.heartbeatLevel" placeholder="在场景中的心跳指数" />
      </el-form-item>
      <el-form-item label="⻆⾊扮演" prop="rpg">
        <el-input v-model="formData.rpg" placeholder="在场景中娃娃的⻆⾊是" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as StoryApi from '@/api/lm/story'
import CustomUploadFile from "@/components/CustomUploadFile/index.vue";
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref
const defaultFileList:any = ref([]) // 默认的文件列表
const roleList = ref([]);
const formData = ref({
  id: "",
  roleId: "",
  name: "",
  rpg: "",
  heartbeatLevel: "",
  duration: 0,
  fileId: "",
  prompt: "",
});
const formRules = reactive({
  roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  fileId: [{ required: true, message: '请上传文件', trigger: 'blur' }],
  name: [{ required: true, message: '请填写场景名称', trigger: 'blur' }],
  rpg: [{ required: true, message: '请填写角色扮演', trigger: 'blur' }],
  heartbeatLevel: [{ required: true, message: '请填写心跳指数', trigger: 'blur' }],
})

const uploadFinish = (e:any)=> {
  let successList = e.successList;

  if(!successList) {
    return message.warning("没有文件上传成功，请检查");
  }

  let fileId = "";
  let name = "";
  let audioDuration = 0;
  if(successList.length) {
    fileId = successList[0].fileId;
    audioDuration = successList[0].audioDuration;
    name = successList[0].file.name.substring(0, successList[0].file.name.lastIndexOf("."));
  }

  formData.value.fileId = fileId;
  formData.value.name = name;
  formData.value.duration = audioDuration;
}


/** 打开弹窗 */
const open = async (options:any) => {
  let type = options.type;
  let id = options.id;
  roleList.value = options.roleList;
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  formData.value = {
    id: "",
    roleId: "",
    name: "",
    rpg: "",
    heartbeatLevel: "",
    duration: 0,
    fileId: "",
    prompt: "",
  };
  defaultFileList.value = [];
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await StoryApi.getStory(id)
      Object.assign(formData.value, data);
      defaultFileList.value = [{
        fileId: formData.value.fileId,
        fileUrl: formData.value.fileUrl
      }];
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.roleId = options.roleId;
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data:any = {
      ...formData.value
    }
    if (formType.value === 'create') {
      await StoryApi.createStory(data)
      message.success(t('common.createSuccess'))
    } else {
      await StoryApi.updateStory(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
